<?php

namespace App\Http\Controllers\Home;

use App\Models\Areas;
use App\Models\BalanceLogs;
use App\Models\BidLists;
use App\Models\Buys;
use App\Models\Categorys;
use App\Models\CompanyInfos;
use App\Models\Configs;
use App\Models\Demands;
use App\Models\Footprints;
use App\Models\IntegralLogs;
use App\Models\Mails;
use App\Models\ProfitLogs;
use App\Models\Users;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;


class DemandController extends Controller
{
    /**
     * HR发布需求页面
     * @param url home.demand.demandAdd
     */
    public function demandAdd(){
        $user_id = auth()->guard('web')->id();
        $userinfo = Users::where('id',$user_id)->value('status');
        if(empty($user_id) || empty($userinfo)){
            return redirect(route('home.login.login'));
        }else{
            return view('home.demand.add');
        }

    }

    /**
     * 需求列表页面
     * @param url home.demand.demandList
     */
    public function demandList(){
        return view('home.demand.list');
    }

    /**
     * HR需求详情页面
     * @param url home.demand.demandHRDetails
     */
    public function demandHRDetails(){
        return view('home.demand.hr_details');
    }

    /**
     * 供应商需求详情页面
     * @param url home.demand.demandSupplierDetails
     */
    public function demandSupplierDetails(){
        return view('home.demand.supplier_details');
    }


    /**
     * HR发布需求
     * @param url home.demand.demandAddApi
     * @param Request $request
     * @param cid 分类id（数组）
     * @param title 需求标题
     * @param content 需求描述
     * @param price 预算（单位：万）
     * @param area 需求区域
     * @param end_at 截止时间
     * @param company_name 公司名称
     * @param company_type 公司类型
     * @param company_size 公司规模
     * @param company_industry 公司行业
     * @param link_name 联系人
     * @param link_phone 联系人电话
     * @param link_department 联系人部门
     * @param link_position 联系人职位
     * @param other 其他
     * @return bool
     */
    public function demandAddApi(Request $request){
        try{
            $user_id = auth()->guard('web')->id();//获取当前登录用户
            if (empty($user_id)) return response()->json($data = ["code"=>300,"data"=>null,"msg"=>'请先登录'], $status = 307);
            $userinfo = Users::where(['id'=>$user_id, 'status'=>1])->first(['username','type']);
            if (empty($userinfo)) return $this->writeJson(1,null,'用户不存在');
            if($userinfo['type'] != 1)  return $this->writeJson(1,null,'供应商不能发布需求');

            $params = [
                'user_id' => $user_id,
                'user_name' => $userinfo['username'],
                'cate_pid' => (int)$request->post('cate_pid'),
                'cate_id' => (int)$request->post('cate_id'),
                'title' => (string)$request->post('title'),
                'content' => (string)$request->post('content'),
                'price' => (string)$request->post('price'),
                'area' => (int)$request->post('area'),
                'end_at' => (string)$request->post('end_at'),
                'company_name' => (string)$request->post('company_name'),
                'company_type' => (int)$request->post('company_type'),
                'company_size' => (int)$request->post('company_size'),
                'company_industry' => (int)$request->post('company_industry'),
                'link_name' => (string)$request->post('link_name'),
                'link_phone' => (string)$request->post('link_phone'),
                'link_department' => (string)$request->post('link_department'),
                'link_position' => (string)$request->post('link_position'),
                'other' => (string)$request->post('other'),
            ];
            if(!preg_match('/^((13|14|15|16|17|18)[0-9]\d{8})$/', $params['link_phone']))   return $this->writeJson(1,null,'请填写正确的手机号码');
            Demands::create($params);
            //HR发布需求送积分
            $integral = Configs::getConfig('integral');
            Users::where('id',$user_id)->increment('integral',$integral['hr_demand']);
            //添加日志记录
            $integral = [
                'user_id' => $user_id,
                'user_name' => $userinfo['username'],
                'integral' => '+'.$integral['hr_demand'],
                'desc' => '发布需求送积分',
                'type' => 1,
            ];
            IntegralLogs::create($integral);
            return $this->writeJson(0, null, '发布成功,请等待平台审核!');
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 需求列表
     * @param url home.demand.demandListsApi
     * @param Request $request
     * @param cid 一级分类id
     * @param cid_id 二级分类id
     * @param area 区域id
     * @param bid 2投标中 3已完成
     * @param urgent 是否加急 1否 2是
     * @param page 页码
     * @param sid 排序 1:需求截止时间 其他或不传:发布时间
     * @param orderby 'desc'倒叙 ‘asc'正序
     * @param end 截止时间 1:一天内 2:三天内 3:七天内 4:一个月内 5:一个月以上
     * @param budget 预算区间 1:0-1万 2:1万-5万 3:5万-10万 4:10万-50万 5:50万-100万 6:100万以上
     * @return bool
     * @return （array）children 二级分类
     * @return （array）demand 活动列表
     * @return （array）area 区域
     */
    public function demandListsApi(Request $request){
        try{
            $params = [
                'cid' => (int)$request->get('cid'),//一级分类id
                'cid_id' => (int)$request->get('cid_id'),//二级分类id
                'area' => (int)$request->get('area'),
                'bid' => (int)$request->get('bid'),//2投标中 3已完成
                'urgent' => (int)$request->get('urgent'),//是否加急 1否 2是
            ];
            if (!empty($params['cid_id'])){
                $params['cid_id'] = explode(",", $params['cid_id']);
            }
            $page = (int)$request->get('page',1);//页码
            $orderby = (string)$request->get('orderby','desc');//排序
            $sid = (int)$request->get('sid');//排序 1:需求截止时间 其他或不传:发布时间
            $end = (string)$request->get('end');//截止时间 1:一天内 2:三天内 3:七天内 4:一个月内 5:一个月以上
            $budget = (string)$request->get('budget');//预算区间 1:0-1万 2:1万-5万 3:5万-10万 4:10万-50万 5:50万-100万 6:100万以上
            //排序
            if ($sid == 1){
                $sort = 'end_at';
            }else{
                $sort = 'created_at';
            }
            //截止时间
            if($end == 1){
                $params['start_time'] = Carbon::now()->startOfDay()->toDateTimeString();
                $params['end_time'] = Carbon::now()->endOfDay()->toDateTimeString();
            }elseif ($end == 2){
                $params['start_time'] = Carbon::now()->startOfDay()->toDateTimeString();
                $params['end_time'] = Carbon::parse('+3 days')->toDateTimeString();
            }elseif ($end == 3){
                $params['start_time'] = Carbon::now()->startOfWeek()->toDateTimeString();
                $params['end_time'] = Carbon::now()->endOfWeek()->toDateTimeString();
            }elseif ($end == 4){
                $params['start_time'] = Carbon::now()->startOfMonth()->toDateTimeString();
                $params['end_time'] = Carbon::now()->endOfMonth()->toDateTimeString();
            }elseif ($end == 5){
                $params['start_time'] = Carbon::now()->endOfMonth()->toDateTimeString();
            }
            //预算区间
            if ($budget == 1){
                $params['price_two'] = 1;
            }elseif ($budget == 2){
                $params['price_one'] = 1;
                $params['price_two'] = 5;
            }elseif ($budget == 3){
                $params['price_one'] = 5;
                $params['price_two'] = 10;
            }elseif ($budget == 4){
                $params['price_one'] = 10;
                $params['price_two'] = 50;
            }elseif ($budget == 5){
                $params['price_one'] = 50;
                $params['price_two'] = 100;
            }elseif ($budget == 6){
                $params['price_one'] = 100;
            }

            $lists = [];
            $lists['cate_id'] = Categorys::getcates(['pid'=>0],['id','name','pid']);//一级分类
            $fields = ['id','title','price','urgent','number','end_at','created_at','content','bid'];
            //二级分类
            if(empty($params['cid'])){
                $lists['children'] = Categorys::where('pid','<>','0')->get(['id','name','pid'])->toArray();
            }else{
                $lists['children'] = Categorys::getcates(['pid'=>$params['cid']],['id','name','pid'])->toArray();
            }
            $lists['demand'] = Demands::allLists($params, $fields, $page, 10, $sort, $orderby);
            foreach ($lists['demand'] as $key=>$val){
                $lists['demand'][$key]['start_at'] = trim(@date('Y-m-d', strtotime($val['created_at'])));
                $lists['demand'][$key]['end_at'] = trim(@date('Y-m-d', strtotime($val['end_at'])));
                $lists['demand'][$key]['price'] = floatval($val['price']);
            }
            $lists['area'] = Areas::get(['id','name','pid']);//服务区域

            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 右侧同类型推荐需求
     * @param url home.demand.rightRecommendDemandApi
     * @param Request $request
     * @param cid 需求一级分类id
     * @return bool
     * @return price 预算 单位：万
     * @return urgent 是否加急:1否 2是
     */
    public function rightRecommendDemandApi(Request $request){
        try{
            $params = [
                'cid' => (int)$request->get('cid'),//需求一级分类id
            ];
            $fields = ['id','title','price','urgent','number','end_at','created_at','content','bid'];
            $lists = Demands::allLists($params, $fields, null, 4, 'end_at', 'asc');
            foreach ($lists as $key=>$val){
                $lists[$key]['start_at'] = trim(@date('Y-m-d', strtotime($val['created_at'])));
                $lists[$key]['end_at'] = trim(@date('Y-m-d', strtotime($val['end_at'])));
                $lists[$key]['price'] = floatval($val['price']);
            }

            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 供应商需求流程
     * @param url home.demand.demandSupplierStepApi
     * @param demand_id 需求id
     * @return step（数组） index：下标 dec：提示 btn：是否可以操作 true可以 false不行 bid_id:投标订单id
     */
    public function demandSupplierStepApi(Request $request){
        try{
            $user_id = auth()->guard('web')->id();//获取当前登录用户
            if (empty($user_id)) return response()->json($data = ["code"=>300,"data"=>null,"msg"=>'请先登录'], $status = 307);
            $userinfo = Users::where(['id'=>$user_id, 'status'=>1])->value('type');
            if (empty($userinfo)) return $this->writeJson(1,null,'用户不存在');

            $demand_id = (int)$request->get('demand_id');
            if (empty($demand_id)) return $this->writeJson(1,null,'参数错误');
            $info = Demands::details(['id'=>$demand_id]);
            if (empty($info)) return $this->writeJson(1,null,'此需求不存在');
            $info['company_type'] = CompanyInfos::where('id',$info['company_type'])->value('name');
            $info['company_industry'] = CompanyInfos::where('id',$info['company_industry'])->value('name');
            $info['company_size'] = CompanyInfos::where('id',$info['company_size'])->value('name');

            $now = date('Y-m-d H:i:s');
            $surplus = $info['limit_num'] - $info['number'];//剩余可投标名额
            //是否可以操作
            $btn = true;
            if($info['end_at'] < $now || $surplus <= 0 || $info['bid'] == 3){
                $btn = false;
            }
            $step = [
                '0' => [
                    'index' => 1,
                    'times' => $now,
                    'content' => '该需求接收' . $info['limit_num'] .'位供应商投标，目前还剩余' . $surplus . '个名额，本次投标需要' . $info['bid_costs'] . '元投标费用。',
                    'dec' => '若你此次中标后，需支付合同总金额的' . $info['service_charge'] . '%的服务费给平台。',
                    'btn' => $btn,
                ],
            ];
            //投标后
            $bid_list = BidLists::details(['demand_id'=>$info['id'],'store_id'=>$user_id]);
            if(!empty($bid_list)){
                $step2 = [
                    'index' => 2,
                    'times' => $now,
                    'content' => '您接收了此需求。',
                    'dec' => '',
                    'btn' => false,
                    'bid_id' => $bid_list['id'],
                ];
                if($bid_list['bid_status'] == 1){
                    $step3 = [
                        'index' => 3,
                        'times' => $now,
                        'content' => '此需求已有人中标，很遗憾！您未能中标。',
                        'dec' => '',
                        'btn' => false,
                    ];
                }elseif ($bid_list['bid_status'] == 2){
                    $step3 = [
                        'index' => 3,
                        'times' => $now,
                        'content' => '您已成功和雇主达成合作，并签订合同。',
                        'dec' => '',
                        'btn' => $btn,
                    ];
                    if ($bid_list['contract_status'] == 2){
                        $step4 = [
                            'index' => 4,
                            'times' => $now,
                            'content' => '您已成功上传合同，请及时支付服务费用。',
                            'dec' => '',
                            'btn' => false,
                        ];
                        if ($bid_list['pay_status'] == 2){
                            $step5 = [
                                'index' => 5,
                                'times' => $now,
                                'content' => '您已成功支付服务费用,订单已完成。',
                                'dec' => '',
                                'btn' => false,
                            ];
                        }
                    }
                }
            }
            if(isset($step2)){
                array_push($step, $step2);
            }
            if(isset($step3)){
                array_push($step, $step3);
            }
            if(isset($step4)){
                array_push($step, $step4);
            }
            if(isset($step5)){
                array_push($step, $step5);
            }
            $info['step'] = $step;

            //添加足迹
            $foot_arr = [
                'user_id' => $user_id,
                'foot_id' => $demand_id,
                'type'    => 2,
            ];
            Footprints::create($foot_arr);
            return $this->writeJson(0,$info);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 供应商投标
     * @param url home.demand.demandSupplierBidApi
     * @param demand_id 需求id
     */
    public function demandSupplierBidApi(Request $request){
        try{
            $user_id = auth()->guard('web')->id();//获取当前登录用户
            if (empty($user_id)) return response()->json($data = ["code"=>300,"data"=>null,"msg"=>'请先登录'], $status = 307);
            $userinfo = Users::where(['id'=>$user_id, 'status'=>1])->first(['username','balance','type']);
            if (empty($userinfo)) return $this->writeJson(1,null,'用户不存在');
            if($userinfo['type'] != 2)  return $this->writeJson(1,null,'HR不能投标');

            $demand_id = (int)$request->post('demand_id');
            if (empty($demand_id)) return $this->writeJson(1,null,'参数错误');
            $demands = Demands::details(['id'=>$demand_id]);
            if (empty($demands)) return $this->writeJson(1,null,'此需求不存在');

            if($userinfo['balance'] < $demands['bid_costs'])  return $this->writeJson(117,null,'余额不足，请充值');

            $bid = BidLists::where(['store_id'=>$user_id,'demand_id'=>$demand_id])->value('id');
            if(!empty($bid)) return $this->writeJson(1,null,$userinfo['username'] . '供应商已经投标该需求,请重新选择');

            $data = [
                'bid_sn' => Buys::makePaySn($user_id),
                'demand_id' => $demand_id,
                'user_id' => $demands['user_id'],
                'user_name' => $demands['user_name'],
                'store_id' => $user_id,
                'store_name' => $userinfo['username'],
                'bid_time' => date('Y-m-d H:i:s'),
                'bid_fee' => $demands['service_charge'],
            ];
            BidLists::create($data);
            Users::where('id',$user_id)->decrement('balance',$demands['bid_costs']);//扣除投标费用
            Demands::where('id',$demand_id)->increment('number', 1);//增加投标数量
            //发送站内信-余额扣除通知
            $mails = [
                'title' => '余额扣除通知',
                'content' => '您已成功投标' . $demands['title'] .',平台已扣除此需求的投标费用'.$demands['bid_costs'].'元。',
                'user_id' => $user_id,
                'status' => 1,
                'type' => 1,
            ];
            Mails::create($mails);
            //余额日志记录
            $balance = [
                'user_id' => $user_id,
                'user_name' => $userinfo['username'],
                'balance' => '-'.$demands['bid_costs'],
                'desc' => '投标扣除余额',
                'type' => 2,
            ];
            BalanceLogs::create($balance);
            return $this->writeJson(0,null, '投标成功');
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 供应商上传合同
     * @param url home.demand.demandUploadContractApi
     * @param demand_id 需求id
     * @param bid_id 投标订单id
     * @param contract_documents 合同文件
     * @param contract_price 合同总金额
     * @param bid_fee 服务费比例
     * @param contract_at 合同签订日期
     * @param pay_end_at 支付截止日期
     */
    public function demandUploadContractApi(Request $request){
        try{
            $user_id = auth()->guard('web')->id();//获取当前登录用户
            if (empty($user_id)) return response()->json($data = ["code"=>300,"data"=>null,"msg"=>'请先登录'], $status = 307);
            $userinfo = Users::where(['id'=>$user_id, 'status'=>1])->first(['username','type']);
            if (empty($userinfo)) return $this->writeJson(1,null,'用户不存在');
            if($userinfo['type'] != 2)  return $this->writeJson(1,null,'HR不能投标');

            $demand_id = (int)$request->post('demand_id');
            $bid_id = (int)$request->post('bid_id');
            if (empty($demand_id) || empty($bid_id)) return $this->writeJson(1,null,'参数错误');
            $demands = Demands::details(['id'=>$demand_id]);
            $bid = BidLists::where(['id'=>$bid_id, 'store_id'=>$user_id, 'demand_id'=>$demand_id])->value('id');
            if(empty($demands) || empty($bid)) return $this->writeJson(1,null,'参数错误');

            $info = BidLists::findOrFail($bid_id);
            $data = [
                'contract_documents' => (string)$request->post('contract_documents'),
                'contract_price' => (string)$request->post('contract_price'),
                'bid_fee' => (string)$request->post('bid_fee'),
                'contract_at' => $request->post('contract_at'),
                'pay_end_at' => $request->post('pay_end_at'),
                'contract_status' => 2,
                'upload_at' => date('Y-m-d H:i:s'),
            ];
            $data['real_fee'] = $data['contract_price'] * ($data['bid_fee']/100);
            $info->update($data);
            //添加收益记录
            $profit = [
                'user_id' => $user_id,
                'user_name' => $userinfo['username'],
                'profit' => $data['contract_price'],
                'desc' => '需求中标合同收益',
                'type' => 2,
            ];
            ProfitLogs::create($profit);
            return $this->writeJson(0,null, '上传成功');
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * HR需求流程
     * @param url home.demand.demandHrStepApi
     * @param demand_id 需求id
     * @return store_name（数组） 已投标供应商
     * @return step（数组） index：下标 dec：提示 btn：是否可以操作 true可以 false不行 bid_id:投标订单id
     */
    public function demandHrStepApi(Request $request){
        try{
            $user_id = auth()->guard('web')->id();//获取当前登录用户
            if (empty($user_id)) return response()->json($data = ["code"=>300,"data"=>null,"msg"=>'请先登录'], $status = 307);
            $userinfo = Users::where(['id'=>$user_id, 'status'=>1])->value('type');
            if (empty($userinfo)) return $this->writeJson(1,null,'用户不存在');

            $demand_id = (int)$request->get('demand_id');
            if (empty($demand_id)) return $this->writeJson(1,null,'参数错误');
            $info = Demands::details(['id'=>$demand_id]);
            if (empty($info)) return $this->writeJson(1,null,'此需求不存在');

            $info['store_name'] = BidLists::allLists(['demand_id'=>$demand_id], ['store_id','store_name'], 50);
            $now = date('Y-m-d H:i:s');
            //是否可以操作
            $btn = true;
            if($info['number'] <= 0){
                $btn = false;
            }
            $step = [
                '0' => [
                    'index' => 1,
                    'times' => $now,
                    'content' => '该需求接收' . $info['limit_num'] .'位供应商投标，目前已有' . $info['number'] . '位供应商参与投标。',
                    'dec' => '',
                    'btn' => $btn,
                ],
            ];
            //供应商投标后
            $bid_list = BidLists::details(['demand_id'=>$info['id'],'user_id'=>$user_id]);
            if(!empty($bid_list)){
                if ($bid_list['bid_status'] == 2){
                    $step2 = [
                        'index' => 2,
                        'times' => $now,
                        'content' => '您已与'.$bid_list['store_name'].'供应商达成合作，并签订合同。',
                        'dec' => '请您于服务结束后评价此次服务，我们将送出现金红包答谢',
                        'btn' => $btn,
                    ];
                    if($info['evaluate_status'] == 2){
                        $step3 = [
                            'index' => 3,
                            'times' => $now,
                            'content' => '您已评价成功。',
                            'dec' => '',
                            'btn' => false,
                        ];
                    }

                }
            }
            if(isset($step2)){
                array_push($step, $step2);
            }
            if(isset($step3)){
                array_push($step, $step3);
            }
            $info['step'] = $step;
            //添加足迹
            $foot_arr = [
                'user_id' => $user_id,
                'foot_id' => $demand_id,
                'type'    => 2,
            ];
            Footprints::create($foot_arr);
            return $this->writeJson(0,$info);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * HR评价此需求
     * @param url home.demand.demandHrEvaluateApi
     * @param demand_id 需求id
     * @param evaluate_content 评价内容
     * @param evaluate_contract 合同文件
     */
    public function demandHrEvaluateApi(Request $request){
        try{
            $user_id = auth()->guard('web')->id();//获取当前登录用户
            if (empty($user_id)) return response()->json($data = ["code"=>300,"data"=>null,"msg"=>'请先登录'], $status = 307);
            $userinfo = Users::where(['id'=>$user_id, 'status'=>1])->first(['username','type']);
            if (empty($userinfo)) return $this->writeJson(1,null,'用户不存在');
            if($userinfo['type'] != 1)  return $this->writeJson(1,null,'供应商不能评价需求');

            $demand_id = (int)$request->post('demand_id');
            if (empty($demand_id)) return $this->writeJson(1,null,'参数错误');
            $demands = Demands::where(['id'=>$demand_id,'user_id'=>$user_id])->value('id');
            if(empty($demands)) return $this->writeJson(1,null,'此需求不存在');

            $info = Demands::findOrFail($demand_id);
            $data = [
                'evaluate_content' => (string)$request->post('evaluate_content'),
                'evaluate_contract' => (string)$request->post('evaluate_contract'),
                'evaluate_status' => 2,
                'evaluate_at' => date('Y-m-d H:i:s'),
            ];
            $info->update($data);
            return $this->writeJson(0,null, '评价成功');
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

}